# -*- encoding:utf8 -*-

import sys
from django.conf import settings
from attendance.excel import excel07_2list
from leave_application.leave_apply import submit_leave
from leave_application.check import approve_leave_app
from staff.models import StaffInfo
from attendance.tool_func import get_or_none
from attendance.convert import dt2str
from datetime import datetime
import re

def import_leaves(file_contents):
    dummy_weixin()
    try:
        ls=excel07_2list(excel_content=file_contents)
        parse_ls(ls)
        success_list=[]
        for l in parse_ls(ls):
            submit_and_approve(l['staff'], l['category'], l['start_time'], l['end_time'])
            success_list.append(l['id'])
        return {'status':'over','success_list':success_list}
    except Exception as e:
        return {'error':'%s\n%s'%(str(e),sys.exc_info()[-1].tb_lineno),'success_list':success_list}
    finally:
        restore_weixin()

def parse_ls(ls):
    head=ls[0]
    id_index=head.index('id')
    empid_index=head.index('empid')
    start_index=head.index('start_time')
    end_index=head.index('end_time')
    category_index=head.index('category')
    
    for leave in ls[1:]:
        staff=get_or_none(StaffInfo,employee_id=leave[empid_index])
        if not staff:
            continue     
        start_time=adapte_time(leave[start_index])
        end_time=adapte_time(leave[end_index])
        yield {'id':leave[id_index],
               'staff':staff,
               'category':leave[category_index],
               'start_time':start_time,
               'end_time':end_time
               }
        
def adapte_time(excel_time):
    if hasattr(excel_time,'year'):
        return dt2str(excel_time)
    elif re.match(r"\d{4}-\d{1,2}-\d{1,2} \d{1,2}:\d{1,2}", excel_time):
        return excel_time
    elif re.match(r'\d{4}/\d{1,2}/\d{1,2} \d{1,2}:\d{1,2}',excel_time):
        return excel_time.replace('/','-')

def submit_and_approve(staff,category,start_time,end_time):
    leave_app=submit_leave(staff, category, start_time, end_time, reason='auto import')
    approve_leave_app(leave_app)
 
def dummy_weixin():
    sys.old_dummy=settings.DUMMY_WEIXIN
    settings.DUMMY_WEIXIN=False

def restore_weixin():
    settings.DUMMY_WEIXIN=sys.old_dummy
